package org.itboys.baseobject.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.itboys.baseobject.entity.KVConfig;
import org.itboys.baseobject.service.KVConfigService;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * key-value 配置控制层
 * @author weisky2
 *
 */
@RestController 
@RequestMapping("/kvConfig") 
public class KVConfigController extends BaseController{

	@Autowired
	private KVConfigService kvConfigService;
	
	@RequestMapping("/list")
	public void list(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		List<KVConfig> list = kvConfigService.list(param);
		Long count = kvConfigService.count(param);
		JsonPageUtils.renderJsonPage(count, list, response);
	}
	
	@RequestMapping("/getByKey")
	public void getByKey(@RequestParam("key") String key, HttpServletResponse response){
		kvConfigService.getValue(key);
		AjaxUtils.renderJson(response, kvConfigService.getById(key));
	}
	
	@RequestMapping("/save")
	public void save(KVConfig kvConfig, HttpServletResponse response){
		try{
			if(StringUtils.isBlank(kvConfig.getKey())){
				AjaxUtils.renderJson(response, -1);//key值不能不空
			}
			kvConfigService.saveOrUpdate(kvConfig.getKey(), kvConfig.getValue(), kvConfig.getDesc());
			AjaxUtils.renderJson(response, 1);//成功
		}catch(Exception e){
			e.printStackTrace();
			logger.error("KVConfigController.vave error", e);
			AjaxUtils.renderJson(response, -2);//失败
		}
		
	}
	
	@RequestMapping("/delete")
	public void delete(@RequestParam("key") String key, HttpServletResponse response){
		try{
			kvConfigService.deleteAndCachClean(key);
			AjaxUtils.renderJson(response, 1);//成功
		}catch(Exception e){
			e.printStackTrace();
			logger.error("KVConfigController.delete error", e);
			AjaxUtils.renderJson(response, -2);//失败
		}
	}
}
